<?php
require_once "includes/config.php";
require_once "includes/functions.php";
require_once 'includes/class.phpmailer.php';
require_once('AmazonAPI/.config.inc.php');
ob_start();
session_start();
$sessid=session_id();
$msg = "";

$service = new AmazonAPI_FPS_Client(AWS_ACCESS_KEY_ID, 
                                       AWS_SECRET_ACCESS_KEY);
$request =  new AmazonAPI_FPS_Model_PayRequest();


if(isset($_REQUEST['signature']) && !empty($_REQUEST['signature'])) {
	$tokenID = $_REQUEST['tokenID'];
	$callerReference = $_REQUEST['callerReference'];
	//print_r($_SESSION); exit;
									   
	$total_recipients = count($_SESSION['recipient_tokens']);
	$loop_limit = ($total_recipients - 1);
	for($i=0;$i<=$loop_limit;$i++){
		
		//echo $_SESSION['recipient_tokens'][$i]."<br />"; exit;
		$request->setCallerDescription('Swapen');
		$request->setCallerReference("swapen".rand());
		
		$request->setMarketplaceVariableFee('1.1');
		$request->setRecipientTokenId($_SESSION['recipient_tokens'][$i]);
		
		$request->setSenderTokenId($tokenID);//set the proper senderToken here.
		
		$amount = new AmazonAPI_FPS_Model_Amount();
		$amount->setCurrencyCode("USD");
		$amount->setValue($_SESSION['recipient_amounts'][$i]); //set the transaction amount here;
		
		$request->setTransactionAmount($amount);
	
		// object or array of parameters
	  	$return = invokePay($service, $request);
		//$return=true;
		
		
					
		
		if($return  && $return[2]!="Failure"){
			$user_id = $_SESSION['user_id_sess'];
			$item_arr = $_SESSION['item_arr'];
			$item_id=$item_arr[0];
			$tempID_arr = $_SESSION['tempID_arr'];
			$transaction_ID = $tempID_arr[0];
			$item_code = $_SESSION['item_code'];
			$item_code = $item_code[0];
			
			
			$i_qry = mysql_query("select owner_id,seller_id,product_id from tbl_items where item_id='".$item_id."'") or die(mysql_error());
			$c_qry = mysql_num_rows($i_qry);
			if($c_qry > 0)
			{
				$selitem = mysql_fetch_array($i_qry);
				$qp = mysql_query("select product_name from tbl_product where product_id='".$selitem['product_id']."'") or die(mysql_error()); 
				$product = mysql_fetch_array($qp);
				if($product)
					$pro_name = $product['product_name'];
				else
					$pro_name = '';
				
				if($selitem['owner_id']==$user_id) 
				{
					//CODE TO REFUND BUYER HERE
					$qry = mysql_query("update tbl_orders set refund=1 where transaction_ID='".$transaction_ID."'") or die(mysql_error());
					
					$qry1 = mysql_query("update tbl_items_code set isSold=0 where code='".$item_code."'") or die(mysql_error());
					
					$sql = mysql_query("select * from tbl_orders where transaction_ID='".$transaction_ID."'") or die(mysql_error());
					$cnt = mysql_num_rows($sql);
					if($cnt > 0)
					{
						$selOrder 	= mysql_fetch_array($sql);
						extract($selOrder);
						
						$email_of_buyer = getUser_email($ordered_by);
						
						$buyers_name = getUser_first_last_name($ordered_by);
						
						$o_qry = mysql_query("select owner_id from tbl_items where item_id=$item_id") or die(mysql_error());
						$items = mysql_fetch_array($o_qry);
						$owner_id = $items['owner_id'];
						$owner_username = getUser($owner_id);
						
						//Code for email to buyer for refund success:starts 
						$email_content = getEmail_content(11); //Order Amount Refunded
						extract($email_content);
						
						$find = array('##_FirstName','##_LastName','##_username','##_pro_name');
						$rep = array($buyers_name['first_name'],$buyers_name['last_name'],$owner_username,$pro_name);
						
						$emailContent=str_replace($find,$rep,$email_body);
						
						$mailmsg="<table width='100%' border='0' style='font-family:Verdana, Arial, Helvetica, sans-serif;font-size:12px; line-height:25px'>
						<tr>
							<td width='18%' height='41'>
								<table width='100%' border='0'>
									<tr>
										<td width='19%' height='68'><img src='".$base_url."images/logo.png'></td>
										<td width='81%'> </td>
									</tr>
								</table>
							</td>
						</tr>
						<tr>
							<td height='32' colspan='2' style='font-family:Verdana, Arial, Helvetica, sans-serif;font-size:11px;'>".$emailContent."</td>
						</tr></table>";
						$email_of_buyer.=',mauzzam@adroitcoders.com';
						
						$email_subject;
						$mail = new PHPMailer(); // defaults to using php "mail()"
						$mail->MsgHTML($mailmsg);
						$mail->From       = "mail@swapen.com";
						$mail->FromName   = "Swapen.com";
						$mail->Subject    = $email_subject;
						$mail->AddAddress($email_of_buyer);
						$mail->Send();
						
						//Code for email to buyer for refund success:ends
						
						//Code for emai to third party user commission refund:starts
						if($order_comm_to_user_id!=0)
						{
							$order_comm_to_name = getUser_first_last_name($order_comm_to_user_id);
							$email_order_comm_to = getUser_email($order_comm_to_user_id);
						
							$email_content = getEmail_content(13); //third party commission refund
							extract($email_content);
							
							$find = array('##_FirstName','##_LastName','##_username','##_commissionearned','##_nameofproduct');
							$rep  = array($order_comm_to_name['first_name'],$order_comm_to_name['last_name'],$_SESSION['user_name'],$order_comm,$pro_name);
							$emailContent=str_replace($find,$rep,$email_body);
							
							
							$mailmsg="<table width='100%' border='0' style='font-family:Verdana, Arial, Helvetica, sans-serif;font-size:12px; line-height:25px'>
							<tr>
								<td width='18%' height='41'>
									<table width='100%' border='0'>
										<tr>
											<td width='19%' height='68'><img src='".$base_url."images/logo.png'></td>
											<td width='81%'> </td>
										</tr>
									</table>
								</td>
							</tr>
							<tr>
								<td height='32' colspan='2' style='font-family:Verdana, Arial, Helvetica, sans-serif;font-size:11px;'>".$emailContent."</td>
							</tr></table>";
							$email_order_comm_to.=', mauzzam@adroitcoders.com';
							$mail = new PHPMailer(); // defaults to using php "mail()"
							$mail->MsgHTML($mailmsg);
							$mail->From       = "mail@swapen.com";
							$mail->FromName   = "Swapen.com";
							$mail->Subject    = $email_subject;
							$mail->AddAddress($email_order_comm_to);
							$mail->Send();
						}
						//Code for emai to third party user commission refund:ends
						
						
						//Code for email to reffered user if any:starts
						$q = mysql_query("select refer_by_user_id,isPaid,refer_comm from tbl_refer_comm where refer_to_user_id=$owner_id and item_id=$item_id and transaction_id='".$transaction_ID."'") or die(mysql_error());
						$cnt_ref_com = mysql_num_rows($q);
						if($cnt_ref_com > 0)
						{
							$selrefercomm=mysql_fetch_array($q);
							
							$refer_by_name = getUser_first_last_name($refer_by_user_id);
							$email_of_refer = getUser_email($refer_by_user_id);
							extract($selrefercomm);
							
							$email_content = getEmail_content(12); //commission refund for referral
							if($email_content)
							{
								extract($email_content);
								$find = array('##_FirstName','##_LastName','##_commAmt');
								$rep  = array($refer_by_name['first_name'],$refer_by_name['last_name'],$refer_comm);
								
								$emailContent=str_replace($find,$rep,$email_body);
								
								$mailmsg="<table width='100%' border='0' style='font-family:Verdana, Arial, Helvetica, sans-serif;font-size:12px; line-height:25px'>
								<tr>
									<td width='18%' height='41'>
										<table width='100%' border='0'>
											<tr>
												<td width='19%' height='68'><img src='".$base_url."images/logo.png'></td>
												<td width='81%'> </td>
											</tr>
										</table>
									</td>
								</tr>
								<tr>
									<td height='32' colspan='2' style='font-family:Verdana, Arial, Helvetica, sans-serif;font-size:11px;'>".$emailContent."</td>
								</tr></table>";
								$email_of_refer.=', mauzzam@adroitcoders.com';
								$mail = new PHPMailer(); // defaults to using php "mail()"
								$mail->MsgHTML($mailmsg);
								$mail->From       = "mail@swapen.com";
								$mail->FromName   = "Swapen.com";
								$mail->Subject    = $email_subject;
								$mail->AddAddress($email_of_refer);
								$mail->Send();
							}
						}
						
						//Code for email to reffered user if any:ends
					}
				}
				else
				{
					//CODE TO REFUND COMMISSION TO OWNER HERE
					$qry = mysql_query("update tbl_orders set refund_comm=1 where transaction_ID='".$transaction_ID."'") or die(mysql_error());
					
					$sql = mysql_query("select * from tbl_orders where transaction_ID='".$transaction_ID."'") or die(mysql_error());
					$cnt = mysql_num_rows($sql);
					if($cnt > 0)
					{
						$selOrder 	= mysql_fetch_array($sql);
						extract($selOrder);
						
						$email_of_owner 	= getUser_email($order_comm_by_user_id);
						$owner_name 		= getUser_first_last_name($order_comm_by_user_id);
						$seller_username 	= getUser($order_comm_to_user_id);
						
						//Code for email to owner to inform that commission has been refunded successfuly:starts 
						$email_content = getEmail_content(14); //commission refunded to owner
						extract($email_content);
						
						$find = array('##_FirstName','##_LastName','##_username','##_comm_amt');
						$rep  = array($owner_name['first_name'],$owner_name['last_name'],$seller_username,$order_comm);
						$emailContent=str_replace($find,$rep,$email_body);
						
						$mailmsg="<table width='100%' border='0' style='font-family:Verdana, Arial, Helvetica, sans-serif;font-size:12px; line-height:25px'>
						<tr>
							<td width='18%' height='41'>
								<table width='100%' border='0'>
									<tr>
										<td width='19%' height='68'><img src='".$base_url."images/logo.png'></td>
										<td width='81%'> </td>
									</tr>
								</table>
							</td>
						</tr>
						<tr>
							<td height='32' colspan='2' style='font-family:Verdana, Arial, Helvetica, sans-serif;font-size:11px;'>".$emailContent."</td>
						</tr></table>";
						$email_of_owner.=', mauzzam@adroitcoders.com';
						$mail = new PHPMailer(); // defaults to using php "mail()"
						$mail->MsgHTML($mailmsg);
						$mail->From       = "mail@swapen.com";
						$mail->FromName   = "Swapen.com";
						$mail->Subject    = $email_subject;
						$mail->AddAddress($email_of_owner);
						$mail->Send();
						//Code for email to owner to inform that commission has been refunded successfuly:ends 
					}
				}
			
			}
			
				
			
			$_SESSION['order_msg'] = "Your transaction is successfull";
			
			header("location:index.php?mySwapen");
		}
		else
		{
			header("location:index.php?mySwapen");
		}
	}
	 
	//use the above token ID to pay
}
function invokePay(AmazonAPI_FPS_Interface $service, $request) 
  {
      try {
              $response = $service->pay($request);
			  //$res_arr = array();
			  if($response){
			  	$payResult = $response->getPayResult();
				//$PayResult = $response->getPayResult();
				$TransactionId = $payResult->getTransactionId();
				$TransactionStatus = $payResult->getTransactionStatus();
				$responseMetadata = $response->getResponseMetadata();
				$RequestId = $responseMetadata->getRequestId();
			  	$res_arr = array($PayResult,
								 $TransactionId,
								 $TransactionStatus,
								 $RequestId
				);
			  }
			  return $res_arr;
              
                

     } catch (AmazonAPI_FPS_Exception $ex) {
         echo("Caught Exception: " . $ex->getMessage() . "\n");
         echo("Response Status Code: " . $ex->getStatusCode() . "\n");
         echo("Error Code: " . $ex->getErrorCode() . "\n");
         echo("Error Type: " . $ex->getErrorType() . "\n");
         echo("Request ID: " . $ex->getRequestId() . "\n");
         echo("XML: " . $ex->getXML() . "\n");
		 return false;
     }
 }
?>